package logic

import (
	"cart_srv/cache"
	"context"
	"fmt"
	"strconv"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCartLogic {
	return &ListCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListCartLogic) ListCart(in *cart.ListCartRequest) (*cart.ListCartResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("cart_%d_*", in.UserId)
	keys := cache.Rdb.Keys(context.Background(), key).Val()

	if len(keys) == 0 {
		return &cart.ListCartResponse{}, nil
	}

	var listCart []*cart.ListCart
	for _, s := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(context.Background(), s).Result()

		goodsId, _ := strconv.Atoi(goodsMap["goods_id"])
		goodsPrice, _ := strconv.ParseFloat(goodsMap["goods_price"], 64)
		num, _ := strconv.Atoi(goodsMap["num"])

		listCart = append(listCart, &cart.ListCart{
			GoodsId:    int64(goodsId),
			GoodsTitle: goodsMap["goods_title"],
			GoodsPrice: float32(goodsPrice),
			Num:        int64(num),
		})
	}
	return &cart.ListCartResponse{
		UserId: in.UserId,
		List:   listCart,
	}, nil
}
